package com.kaola.action;

import java.util.List;

import com.kaola.pojo.Product;
import com.kaola.pojo.UserProduct;
import com.kaola.service.ProductService;
import com.kaola.service.UserProductService;
import com.kaola.util.FieldUtils;
import com.opensymphony.xwork2.ActionSupport;

public class UserProductAction extends ActionSupport {
	
	private UserProduct userProduct;
	private List<UserProduct> userProducts;
	
	private UserProductService userProductService;
	private ProductService productService;

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public List<UserProduct> getUserProducts() {
		return userProducts;
	}

	public void setUserProducts(List<UserProduct> userProducts) {
		this.userProducts = userProducts;
	}

	public UserProduct getUserProduct() {
		return userProduct;
	}

	public void setUserProduct(UserProduct userProduct) {
		this.userProduct = userProduct;
	}

	public UserProductService getUserProductService() {
		return userProductService;
	}

	public void setUserProductService(UserProductService userProductService) {
		this.userProductService = userProductService;
	}
	
	public String create() {
		if (userProduct.getUser().getId() == 0) {
			return LOGIN;
		}
		if (!userProductService.isExist(userProduct.getUser().getId(), userProduct.getProduct().getId())) {
			userProduct.setProduct(productService.get(userProduct.getProduct().getId()));
			userProduct.setBuyNum(userProductService.correctionBuyNum(userProduct.getBuyNum(), userProduct.getProduct().getInventory()));
			FieldUtils.generateDefaultField(userProduct);
			userProductService.addToShoppingCart(userProduct);
		}
		userProducts = userProductService.listForShoppingCart(userProduct.getUser());
		return SUCCESS;
	}
	
	public String list() {
		if (userProduct.getUser().getId() == 0) {
			return LOGIN;
		}
		userProducts = userProductService.listForShoppingCart(userProduct.getUser());
		return SUCCESS;
	}
	
	public String update() {
		userProduct.setProduct(productService.get(userProduct.getProduct().getId()));
		userProduct.setBuyNum(userProductService.correctionBuyNum(userProduct.getBuyNum(), userProduct.getProduct().getInventory()));
		FieldUtils.modifyDefaultField(userProduct);
		userProductService.updateToShoppingCart(userProduct);
		userProducts = userProductService.listForShoppingCart(userProduct.getUser());
		return SUCCESS;
	}
	
	public String destroy() {
		userProductService.removeFromShoppingCart(userProduct.getId());
		userProducts = userProductService.listForShoppingCart(userProduct.getUser());
		return SUCCESS;
	}
}
